﻿package net.wangit.view.element.component;

import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.support.AbstractElementWriter;
import net.wangit.util.Checker;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.element.util.ElementUtil;
import net.wangit.view.util.Html;

public class AnchorElementWriter extends AbstractElementWriter {

	public AnchorElementWriter() {
	}

	protected void writeText(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControl(ac, html, ec, row);
	}

	protected void writeTextWithValue(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControl(ac, html, ec, row);
	}

	protected void writeControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControlWithDisplay(ac, html, ec, row, false);
	}

	protected void writeReadOnlyControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeDisabledControl(ac, html, ec, row);
	}

	protected void writeDisabledControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		String value = ElementUtil.getValueOrDefaultWithFormat(ac, ec, row);
		if (!Checker.isEmpty(value))
			Html.set(html, value);
		else
			Html.set(html, ElementUtil.resolveName(ac, ec));
	}

	protected void writeHidden(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControlWithDisplay(ac, html, ec, row, true);
	}

	private void writeControlWithDisplay(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row, boolean hidden) {
		html.append("<a");
		Html.setAttribute(html, ElementUtil.resolveCustom(ac, ec, row));
		Html.setTitle(html, ElementUtil.resolveTitle(ac, ec, row));
		Html.setCss(html, ec.getCss());
		Html.setHerf(html, ElementUtil.resolveLink(ac, ec, row));
		if (hidden)
			html.append(" id=\"").append(ElementUtil.getAlias(ec)).append(
					"\" style=\"display:none\"");
		html.append(">");
		String value = ElementUtil.getValueOrDefaultWithFormat(ac, ec, row);
		if (!Checker.isEmpty(value))
			Html.set(html, value);
		else
			Html.set(html, ElementUtil.resolveName(ac, ec));
		html.append("</a>");
	}
}
